import json

import cv2
import numpy as np
import myfuncs as mf
import os.path as osp


class ColorFilter:
	COLORS_STORE_PATH = 'ColorsConfig.json'
	originImage = None
	grayImage = None
	hsvImage = None

	def __init__(self, src):
		self.originImage = src
		self.grayImage = cv2.cvtColor(self.originImage, cv2.COLOR_BGR2GRAY)
		self.hsvImage = cv2.cvtColor(self.originImage, cv2.COLOR_BGR2HSV)

	def imageResize(self, width):
		self.originImage = mf.resize(self.originImage, width)
		self.grayImage = cv2.cvtColor(self.originImage, cv2.COLOR_BGR2GRAY)
		self.hsvImage = cv2.cvtColor(self.originImage, cv2.COLOR_BGR2HSV)

	def getColor(self, tag, getAll=False):
		if osp.exists(self.COLORS_STORE_PATH):
			with open(self.COLORS_STORE_PATH, 'r') as f:
				allColorsJson = f.read()
			f.close()
			if allColorsJson is not None:
				allColorsPython = json.loads(allColorsJson)
				if getAll:
					return allColorsPython
				else:
					if allColorsPython[tag] is not None:
						rangeMin = allColorsPython[tag]['rangeMin']
						rangeMax = allColorsPython[tag]['rangeMax']
						return [np.array(rangeMin), np.array(rangeMax)]
		else:
			return {}

	def addColor(self, tag, colorRangeMin, colorRangeMax):
		color = {
			'rangeMin': colorRangeMin,
			'rangeMax': colorRangeMax
		}
		existedColors = self.getColor(None, True)
		existedColors[tag] = color
		colorJson = json.dumps(existedColors, indent=2)
		with open(self.COLORS_STORE_PATH, 'w') as f:
			f.write(colorJson)
		f.close()

	def filterColor(self, colorTag):
		rangeMin, rangeMax = self.getColor(colorTag)
		mask = cv2.inRange(self.hsvImage, rangeMin, rangeMax)
		hitArea = cv2.bitwise_and(self.originImage, self.originImage, mask=mask)
		return hitArea, mask


if __name__ == '__main__':
	src = cv2.imread("operand1.jpg")
	colorFilter = ColorFilter(src)
	colorFilter.imageResize(360)
	colorFilter.constructColor("orange", [20, 100, 100], [30, 255, 255])
	colorFilter.constructColor("black", [0, 0, 0], [100, 100, 100])
	orangeArea = colorFilter.filterColor("orange")[0]
	blackArea = colorFilter.filterColor("black")[0]
	showDict = {
		"orange": orangeArea,
		"black": blackArea
	}
	mf.showImages(showDict)
